package com.nforce.linremote.model;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Environment;
import android.util.Log;

import com.nforce.linremote.Constants;
import com.nforce.linremote.scripting.FileHelper;
import com.nforce.linremote.scripting.ScriptHandler;

public class Script {
    private String programName;
    private final List<LButton> buttons = new ArrayList<LButton>();
    private final Map<String, LFunction> functions = new HashMap<String, LFunction>();
    private final Map<String, String> variables = new HashMap<String, String>();
    private final boolean loadedFully;

    public Script(String scriptPath, String interfeiz, boolean loadFull) {
	setVar("interface", interfeiz);
	setVar("sdcard", Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Constants.SCRIPTS_PATH_EXTERNAL);
	if (scriptPath != null) {
	    loadScript(scriptPath, loadFull);
	}
	loadedFully = loadFull;
    }

    public String getProgramName() {
	return programName;
    }

    public void setProgramName(String programName) {
	this.programName = programName;
    }

    public List<LButton> getButtons() {
	return buttons;
    }

    public Map<String, String> getVariables() {
	return variables;
    }

    public void setVar(String name, String var) {
	variables.put(name, var);
    }

    public String getVar(String name) {
	String result = variables.get(name);
	if (result == null) {
	    Log.d(Constants.DEBUG_TAG, "Variable " + name + " not defined.");
	    return null;
	}
	return result;
    }

    public Map<String, LFunction> getFunctions() {
	return functions;
    }

    public void setFunction(String name, LFunction function) {
	functions.put(name, function);
    }

    public LFunction getFunction(String name) {
	LFunction result = functions.get(name);
	if (result == null) {
	    Log.d(Constants.DEBUG_TAG, "Variable " + name + " not defined.");
	    return null;
	}
	return result;
    }

    public boolean isLoadedFully() {
	return loadedFully;
    }

    private void loadScript(String scriptPath, boolean loadFull) {
	InputStream inputStream = FileHelper.getFileForReading(scriptPath);
	try {
	    ScriptHandler dataHandler = new ScriptHandler(this, loadFull);
	    dataHandler.parse(inputStream);
	} catch (Exception pce) {
	    Log.e("SAX XML", "sax parse error", pce);
	}
	try {
	    inputStream.close();
	} catch (IOException e) {
	}
    }
}
